//
//  AppDelegate.m
//  New_Runway
//
//  Created by mack on 2018/1/22.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "AppDelegate.h"
#import <Bugly/Bugly.h>
#import "WXApi.h"
#import "NRWCarNavigationController.h"
#import "NRWCarTabbarController.h"
#import "NRWCarLoginController.h"
#import "IamgeFactory.h"
#import <JSPatchPlatform/JSPatch.h>

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define BUGLY_APP_ID @"b16987dd63"

#import "AppDelegate+MsgPush.h"


@interface AppDelegate ()<BuglyDelegate,WXApiDelegate,UIAlertViewDelegate>
@property (nonatomic, copy) NSString *url;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [JSPatch stwa43:@"5e9f10b78b08e134"];
//    [JSPatch testscjsinbund];
    [JSPatch setupRSAPublicKey:@"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXZnDXzjGEKbd4bqPnKTUQx1UA\nLJN/2NU3C1+7/Wd47SXVCqxrxJg1A2SXCvqHLwwsADX8M52eRJeA/Q/2x9QMy5M3\nS7GeH3tpJPMUJrlvDKbMS5FT4qV0uDuQHeeyh/Z0wh+058pGqV5OaxMiNaNnmTXw\ncYFi6rhtikHezhucZwIDAQAB\n-----END PUBLIC KEY-----"];
    [JSPatch sync];

    [self initWindowWithLaunch:launchOptions];
    [self creatBugly];
    [self wechat];
    [self initJpushWithLaunchOptions:launchOptions];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    UMConfigInstance.appKey = @"5b20de93f43e483fb000011f";
    UMConfigInstance.channelId = @"App Store";
    UMConfigInstance.bCrashReportEnabled = NO;
    [MobClick startWithConfigure:UMConfigInstance];
    [MobClick setAppVersion:[infoDictionary objectForKey:@"CFBundleShortVersionString"]];
    [MobClick setEncryptEnabled:YES];
    
    return YES;
}

-(void)wechat{
    
    [WXApi registerApp:@"wx4123efed415d4f8e"];
}
-(void)creatBugly{
    BuglyConfig * config = [[BuglyConfig alloc] init];
    config.debugMode = YES;
    config.blockMonitorEnable = YES;
    config.blockMonitorTimeout = 1.5;
    config.channel = @"Bugly";
    
    config.delegate = self;
    
    config.consolelogEnable = NO;
    config.viewControllerTrackingEnable = NO;
    // Start the Bugly sdk with APP_ID and your config
    [Bugly startWithAppId:BUGLY_APP_ID
#if DEBUG
        developmentDevice:YES
#endif
                   config:config];
    [Bugly setUserIdentifier:[NSString stringWithFormat:@"User: %@", [UIDevice currentDevice].name]];
    [Bugly setUserValue:[NSProcessInfo processInfo].processName forKey:@"Process"];
}
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    return [WXApi handleOpenURL:url delegate:self];
}
- (void)onReq:(BaseReq *)req
{
    NSLog(@"onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面");
}
- (void)onResp:(BaseResp *)resp
{
    NSLog(@"回调处理");
    
    // 处理 分享请求 回调
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        switch (resp.errCode) {
            case WXSuccess:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"分享成功!"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil, nil];
                [alert show];
            }
                break;
                
            default:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"分享失败!"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil, nil];
                [alert show];
            }
                break;
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//
    
    
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber =0;
    [self setPushBage:0];
    [IamgeFactory reset];
//    [CWAuctionInterface serviceReconnect];
    [self isUpdateAPP];
}
-(void)isUpdateAPP{
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDict objectForKey:@"CFBundleShortVersionString"];
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,updaAPPApi];
    NSDictionary *params = @{
                             @"apkKey":@"anpxdIOSErpApp",
                             @"apkVersion":version
                             };
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            if ([version isEqualToString:response[@"result"][@"apkVersion"]]) {
                return ;
            }
            
            NSString *str = response[@"result"][@"apkVersion"];
            //将版本号按照.切割后存入数组中
            NSArray *localArray = [version componentsSeparatedByString:@"."];
            NSArray *appArray = [str componentsSeparatedByString:@"."];
            NSInteger minArrayLength = MIN(localArray.count, appArray.count);
            BOOL needUpdate = NO;
            for(int i=0;i<minArrayLength;i++){//以最短的数组长度为遍历次数,防止数组越界
                //取出每个部分的字符串值,比较数值大小
                NSString *localElement = localArray[i];
                NSString *appElement = appArray[i];
                NSInteger  localValue =  localElement.integerValue;
                NSInteger  appValue = appElement.integerValue;
                if(localValue<appValue) {
                    needUpdate = YES;
                    break;
                }else{
                    needUpdate = NO;
                }
            }
            if (needUpdate ) {
                
                self.url = response[@"result"][@"apkUrl"];
                if ([response[@"result"][@"apkForce"] integerValue] == 0 ) {//判断版本大小了
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil] ;
                    alert.delegate = self;
                    alert.tag = 10;
                    [alert show];
                    
                }else if ([response[@"result"][@"apkForce"] integerValue] == 1){
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil] ;
                    alert.delegate = self;
                    alert.tag = 11;
                    [alert show];
                }
                
            }
        }
        
    } failBlock:^(NSError *error) {

    }];
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 10) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.url]];
        }
    }else{
        if (buttonIndex == 0) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.url]];
        }
    }
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



@end
